<template>
  <view class="container" :style="appThemeStyle">
    <mescroll-body ref="mescrollRef" :sticky="true" @init="mescrollInit" :down="{ native: true }" @down="downCallback" :up="upOption"
      @up="upCallback">
      <!-- Tab栏 -->
      <u-tabs :list="tabList" :is-scroll="false" v-model="curTab" active-color="#786cff" :duration="0.2" @change="onChangeTab" />
      <!-- 列表数据 -->
      <view class="widget-list">
        <view class="widget__detail dis-flex flex-x-between" v-for="(item, index) in list.data" :key="index">
          <view class="detail__left dis-flex flex-dir-column flex-x-around">
            <view class="detail__money f-30">提现 {{ item.money }}元</view>
            <view class="detail__time col-9 f-24">{{ item.create_time }}</view>
          </view>
          <view class="detail__right dis-flex flex-y-center">
            <view class="detail__status" :class="[ApplyStatusColor[item.apply_status]]">
              <text>{{ ApplyStatusText[item.apply_status] }}</text>
            </view>
            <!-- #ifdef MP-WEIXIN -->
            <view v-if="item.apply_status == ApplyStatusEnum.PASSED.value && item.pay_type == PayTypeEnum.WECHAT2.value"
              class="detail__reason" @click="handleMerchantTransfer(item)">确认收款
            </view>
            <!-- #endif -->
            <view v-if="item.apply_status == ApplyStatusEnum.REJECT.value" class="detail__reason" @click="handleShowRejectReason(item)">驳回原因
            </view>
          </view>
        </view>
      </view>
    </mescroll-body>
    <!-- 驳回原因弹窗 -->
    <u-modal v-model="showRejectReason" title="驳回原因">
      <view class="pops-content">
        <text>{{ rejectReason }}</text>
      </view>
    </u-modal>
  </view>
</template>

<script>
  import MescrollMixin from '@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins'
  import { getEmptyPaginateObj, getMoreListData } from '@/core/app'
  import * as Api from '@/api/dealer/withdraw'
  import SettingModel from '@/common/model/dealer/Setting'
  import { ApplyStatusEnum, PayTypeEnum } from '@/common/enum/dealer/withdraw'

  const pageSize = 15

  // 提现状态文字
  const ApplyStatusText = {}

  // 提现状态颜色
  const ApplyStatusColor = {
    [ApplyStatusEnum.WAIT.value]: 'col-8',
    [ApplyStatusEnum.PASSED.value]: 'col-green',
    [ApplyStatusEnum.REJECT.value]: 'col-m',
    [ApplyStatusEnum.PAYMENT.value]: 'col-green'
  }

  export default {
    mixins: [MescrollMixin],
    data() {
      return {
        // 枚举类
        ApplyStatusEnum,
        PayTypeEnum,
        ApplyStatusColor,
        ApplyStatusText,
        // 选项卡列表
        tabList: [],
        // 当前选项
        curTab: 0,
        // 列表数据
        list: getEmptyPaginateObj(),
        // 上拉加载配置
        upOption: {
          // 首次自动执行
          auto: true,
          // 每页数据的数量; 默认10
          page: { size: pageSize },
          // 数量要大于12条才显示无更多数据
          noMoreSize: 12,
          // 空布局
          empty: {
            tip: '亲，暂无相关数据'
          }
        },
        // 驳回原因弹窗
        showRejectReason: false,
        rejectReason: ''
      }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
      this.getSetting()
    },

    methods: {

      // 获取分销设置
      getSetting() {
        const app = this
        SettingModel.data()
          .then(setting => {
            const words = setting.words.withdraw_list
            app.setPageTitle(words.title)
            app.setTabList(words.words)
            app.setStatusText(words.words)
          })
      },

      // 设置页面标题
      setPageTitle(title) {
        uni.setNavigationBarTitle({
          title: title.value
        })
      },

      // 设置选项卡数据
      setTabList(words) {
        const app = this
        app.tabList = [
          { value: -1, name: words.all.value },
          { value: ApplyStatusEnum.WAIT.value, name: words.apply_10.value },
          { value: ApplyStatusEnum.PASSED.value, name: words.apply_20.value },
          { value: ApplyStatusEnum.REJECT.value, name: words.apply_30.value },
          { value: ApplyStatusEnum.PAYMENT.value, name: words.apply_40.value },
        ]
      },

      // 设置状态文字
      setStatusText(words) {
        const app = this
        app.ApplyStatusText = {
          [ApplyStatusEnum.WAIT.value]: words.apply_10.value,
          [ApplyStatusEnum.PASSED.value]: words.apply_20.value,
          [ApplyStatusEnum.REJECT.value]: words.apply_30.value,
          [ApplyStatusEnum.PAYMENT.value]: words.apply_40.value
        }
      },

      /**
       * 上拉加载的回调 (页面初始化时也会执行一次)
       * 其中page.num:当前页 从1开始, page.size:每页数据条数,默认10
       * @param {Object} page
       */
      upCallback(page) {
        const app = this
        // 设置列表数据
        app.getList(page.num)
          .then(list => {
            const curPageLen = list.data.length
            const totalSize = list.total
            app.mescroll.endBySize(curPageLen, totalSize)
          })
          .catch(() => app.mescroll.endErr())
      },

      // 获取提现列表
      getList(pageNo = 1) {
        const app = this
        return new Promise((resolve, reject) => {
          Api.list({ applyStatus: app.getTabValue(), page: pageNo })
            .then(result => {
              // 合并新数据
              const newList = result.data.list
              app.list.data = getMoreListData(newList, app.list, pageNo)
              resolve(newList)
            })
        })
      },

      // 获取当前标签项的值
      getTabValue() {
        const app = this
        if (app.tabList.length) {
          return app.tabList[app.curTab].value
        }
        return -1
      },

      // 切换标签项
      onChangeTab(index) {
        const app = this
        // 设置当前选中的标签
        app.curTab = index
        // 刷新列表数据
        app.onRefreshList()
      },

      // 刷新列表数据
      onRefreshList() {
        this.list = getEmptyPaginateObj()
        setTimeout(() => this.mescroll.resetUpScroll(), 120)
      },

      // 显示驳回原因
      handleShowRejectReason(item) {
        this.showRejectReason = true
        this.rejectReason = item.reject_reason
      },

      // 用户确认收款
      // #ifdef MP-WEIXIN
      async handleMerchantTransfer(item) {
        const app = this
        if (!wx.canIUse('requestMerchantTransfer')) {
          app.$error('你的微信版本过低，请更新至最新版本')
          return
        }
        // 向后端发起转账请求
        const { data } = await Api.mchTransfer(item.id)
        // 显示微信弹窗提醒用户确认收款
        wx.requestMerchantTransfer({
          mchId: data.mchId,
          appId: data.appId,
          package: data.package_info,
          async success(res) {
            // res.err_msg将在页面展示成功后返回应用时返回ok，并不代表收款成功
            console.log('wx.requestMerchantTransfer [success]:', res)
            // app.$error('success:', res)
            // 同步查询并更新转账单记录状态
            await Api.queryBillsNotice({ outBillNo: data.out_bill_no })
            // 刷新列表数据
            setTimeout(() => app.onRefreshList(), 1000)
          },
          fail(res) {
            console.log('wx.requestMerchantTransfer [fail]:', res)
            if (res.result != 'cancel') {
              app.$error(res.errMsg)
            }
          }
        })
      }
      // #endif

    }
  }
</script>

<style>
  page {
    background: #fff;
  }
</style>
<style lang="scss" scoped>
  // 提现明细列表
  .widget-list {
    padding: 16rpx 20rpx 40rpx 20rpx;
    box-sizing: border-box;
  }

  .widget__detail {
    padding: 26rpx 15rpx;
    box-sizing: border-box;
    font-size: 26rpx;
    border-bottom: 1rpx solid #f2f2f2;

    .detail__money {
      font-size: 30rpx;
    }

    .detail__reason {
      color: #8e84fc;
      // margin-top: 10rpx;
      margin-left: 20rpx;
    }

  }

  // 驳回原因 (弹窗)
  .pops-content {
    padding: 30rpx 48rpx;
    font-size: 28rpx;
    line-height: 44rpx;
    text-align: left;
    color: #606266;
    height: 220rpx;
    box-sizing: border-box;
  }
</style>